/**
 * @Title: AlertDialogUtil.java
 * @author Mengting Lu
 * @date 2015年8月3日 下午2:14:26
 */
package com.shanghaionstar.utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.view.WindowManager;
import android.widget.TextView;

import com.onstar.cn.common.exception.HttpException;
import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.log.LogManager;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.DeviceUtil;
import com.onstar.cn.mag.enumtype.RemoteCommandsType;
import com.onstar.cn.vehicle.entity.ErrorInfo;
import com.shanghaionstar.OnstarApplication;
import com.shanghaionstar.R;
import com.shanghaionstar.login.LoginActivity;
import com.shanghaionstar.sqlite.UserAddressInfoImpl;

import java.lang.reflect.Field;

/**
 * @author Mengting Lu
 * @ClassName: AlertDialogUtil
 * @Description: TODO
 * @date 2015年8月3日 下午2:14:26
 */
public class AlertDialogUtil {
    private static final LogManager logger = LogManager.getInstance();

    public static void showAlertDialog(Context context, String title, String message, OnClickListener listener) {
        logger.d("showAlertDialog(Context context, String title, String message) start:title=" + title + " message="
                + message);
        if (listener == null) {
            showAlertDialog(context, title, message);
            return;
        }
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);

        alertDialog.setMessage(message);
        alertDialog.setPositiveButton(R.string.submit, listener);
        if (isAllowShowDialog(context)) {
            alertDialog.show();
        }
    }

    public static void showAlertDialog(Context context, String title, String message, boolean cancelable, OnClickListener listener) {
        logger.d("showAlertDialog(Context context, String title, String message) start:title=" + title + " message="
                + message);
        if (listener == null) {
            showAlertDialog(context, title, message);
            return;
        }
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);

        alertDialog.setMessage(message);
        alertDialog.setCancelable(cancelable);
        alertDialog.setPositiveButton(R.string.submit, listener);
        if (isAllowShowDialog(context)) {
            alertDialog.show();
        }
    }

    public static void showAlertDialog(Context context, String title, String message, OnClickListener listener, OnClickListener cancel) {
        logger.d("showAlertDialog(Context context, String title, String message) start:title=" + title + " message="
                + message);
        if (listener == null) {
            showAlertDialog(context, title, message);
            return;
        }
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);

        alertDialog.setMessage(message);
        alertDialog.setPositiveButton(R.string.submit, listener);
        alertDialog.setNegativeButton(R.string.cancel, cancel);
        if (isAllowShowDialog(context)) {
            alertDialog.show();
        }
    }

    public static void showAlertDialog(Context context, String title, String message, OnClickListener listener,
                                       boolean isCancel) {
        logger.d("showAlertDialog(Context context, String title, String message) start:title=" + title + " message="
                + message);
        if (listener == null) {
            showAlertDialog(context, title, message);
            return;
        }
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);

        alertDialog.setMessage(message);
        alertDialog.setPositiveButton(R.string.submit, listener);
        if (isCancel) {
            alertDialog.setNegativeButton(R.string.share_cancel, null);
        }
        if (isAllowShowDialog(context)) {
            alertDialog.show();
        }
    }

    private static void showLogin(String message, Context context) {
        //如果报出的Error code是登录失效，则自动退出登录
        if (!CommonUtil.isNull(message) && (message.equalsIgnoreCase(context.getString(R.string.L7_invalid_token)))) {
            UserAddressInfoImpl userAddressInfoImpl = new UserAddressInfoImpl(context);
            userAddressInfoImpl.deleteTableInfo();
//            context.sendBroadcast(new Intent("MainTabActivity.loginOutReceiver"));
            OnstarApplication onstarApplication = (OnstarApplication) context.getApplicationContext();
            if (onstarApplication != null) {
                onstarApplication.setHeadImgRes(null);
                onstarApplication.setRes(null);
            }
            AuthorUtil.getInstance().loginOut(context);
            Intent it = new Intent(context, LoginActivity.class);
            context.startActivity(it);
        }
    }

    public static void showAlertDialog(Context context, String title, String message, int resId,
                                       OnClickListener listener, boolean isCancel) {
        logger.d("showAlertDialog(Context context, String title, String message) start:title=" + title + " message="
                + message);
        if (listener == null) {
            showAlertDialog(context, title, message);
            return;
        }
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);

        alertDialog.setMessage(message);
        alertDialog.setPositiveButton(resId, listener);
        if (isCancel) {
            alertDialog.setNegativeButton(R.string.share_cancel, null);
        }
        showDialog(context, alertDialog);
    }

    private static boolean isAllowShowDialog(Context context) {
        if (context instanceof Activity) {
            Activity activity = (Activity) context;
            return !activity.isFinishing();
        }
        return true;
    }

    private static void showDialog(Context context, AlertDialog.Builder alertDialog) {
        if (isAllowShowDialog(context)) {
            try {
//				alertDialog.show();
                // AlertDialog dialog = alertDialog.create();
                requetFocusable(alertDialog, context);
                // dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
                // dialog.show();
            } catch (OutOfMemoryError e) {
                e.printStackTrace();
            }
        }
    }

    private static void showSystemDialog(Context context, AlertDialog.Builder alertDialog) {
        try {
            AlertDialog dialog = alertDialog.create();
            dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
            dialog.show();
        } catch (OutOfMemoryError e) {
            e.printStackTrace();
        }
    }

    public static void showAlertDialog(final Context context, String title, final String message) {
        logger.d("showAlertDialog(Context context, String title, String message) start:title=" + title + " message="
                + message);

        AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);

        alertDialog.setMessage(message);
        alertDialog.setPositiveButton(R.string.submit, new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                showLogin(message, context);
            }
        });
        showDialog(context, alertDialog);
    }

    public static void showConfigureDialog(final Context context, String title, final String message, String btnText, OnClickListener clickListener) {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);

        alertDialog.setMessage(message);
        alertDialog.setPositiveButton(btnText, clickListener);
        alertDialog.setNegativeButton(R.string.cancel, null);
        showDialog(context, alertDialog);
    }

//	private static void showLogin(String message,Context context){
//		//如果报出的Error code是登录失效，则自动退出登录
//		if(!CommonUtil.isNull(message)&&(message.equalsIgnoreCase(context.getString(R.string.L7_invalid_token)))){
//			UserAddressInfoImpl userAddressInfoImpl = new UserAddressInfoImpl(context);
//			userAddressInfoImpl.deleteTableInfo();
//			context.sendBroadcast(new Intent("MainTabActivity.loginOutReceiver"));
//			OnstarApplication onstarApplication= (OnstarApplication) context.getApplicationContext();
//			if(onstarApplication!=null) {
//				onstarApplication.setHeadImgRes(null);
//				onstarApplication.setRes(null);
//			}
//			Intent it = new Intent(context, LoginActivity.class);
//			context.startActivity(it);
//		}
//	}

    public static void showAlertDialog(final Context context, String title, final String message,
                                       final AlertDialogEventProxy eventProxy) {
        logger.d("showAlertDialog(Context context, String title, String message) start:title=" + title + " message="
                + message);
        if (context == null) {
            return;
        }
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
        alertDialog.create().getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        alertDialog.setMessage(message);
        alertDialog.setPositiveButton(R.string.submit, new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (eventProxy != null)
                    eventProxy.onPositiveClickListener(dialog);
                showLogin(message, context);
            }
        });
        alertDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                if (eventProxy != null)
                    eventProxy.onCancelListener(dialog);
            }
        });
        showDialog(context, alertDialog);
    }

    public static void showSystemAlertDialog(final Context context, String title, final String message,
                                             final AlertDialogEventProxy eventProxy) {
        logger.d("showAlertDialog(Context context, String title, String message) start:title=" + title + " message="
                + message);

        AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
        alertDialog.create().getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        alertDialog.setMessage(message);
        alertDialog.setPositiveButton(R.string.submit, new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (eventProxy != null)
                    eventProxy.onPositiveClickListener(dialog);
                showLogin(message, context);
            }
        });
        alertDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                if (eventProxy != null)
                    eventProxy.onCancelListener(dialog);
            }
        });
        showSystemDialog(context, alertDialog);
    }

    public static void showAlertDialog(Context context, int titleId, int messageId) {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
        alertDialog.setTitle(titleId);
        alertDialog.setMessage(messageId);
        alertDialog.setPositiveButton(R.string.submit, new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        requetFocusable(alertDialog, context);
    }

    public static void showAlertDialog(Context context, int titleId, int messageId, OnClickListener listener,
                                       int cancelResId) {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);

        alertDialog.setMessage(messageId);
        alertDialog.setPositiveButton(R.string.upgrade_to_owner, listener);
        alertDialog.setNegativeButton(R.string.cancel, null);
        requetFocusable(alertDialog, context);
    }

    public static void showAlertDialog(Context context, int messageId, OnClickListener listener,
                                       OnClickListener cancelListener) {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);

        alertDialog.setMessage(messageId);
        alertDialog.setPositiveButton(R.string.submit, listener);
        alertDialog.setNegativeButton(R.string.cancel, cancelListener);
        requetFocusable(alertDialog, context);
    }

    public static void showAlertDialog(Context context, int titleId, int messageId, OnClickListener listener) {
        if (context == null)
            return;
        if (listener == null) {
            showAlertDialog(context, titleId, messageId);
            return;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(context);

        builder.setPositiveButton(R.string.submit, listener);
        builder.setMessage(messageId);
        requetFocusable(builder, context);
    }

    public static void showNotCancelAlertDialog(Context context, int titleId, int messageId, OnClickListener listener) {
        if (listener == null) {
            showAlertDialog(context, titleId, messageId);
            return;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        // 中文版本包含确定按钮
        if (DeviceUtil.getLanguage().equalsIgnoreCase("en")) {
            builder.setNegativeButton(R.string.submit, null);
        } else {
            builder.setNegativeButton(R.string.cancel, null);
            builder.setPositiveButton(R.string.submit, listener);
        }
        builder.setMessage(messageId);
        builder.setCancelable(false);
        requetFocusable(builder, context);
    }

    private static void requetFocusable(AlertDialog.Builder builder, Context context) {
        if (isAllowShowDialog(context)) {
            AlertDialog dialog = builder.create();
//            dialog.getWindow().setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(context,R.color.transparent)));
            try {
                dialog.show();

                // 反射获取当前Dialog TextView对象
                Field mAlert = AlertDialog.class.getDeclaredField("mAlert");
                mAlert.setAccessible(true);
                Object alertController = mAlert.get(dialog);
                Field mTitleView = alertController.getClass().getDeclaredField("mMessageView");
                mTitleView.setAccessible(true);
                TextView title = (TextView) mTitleView.get(alertController);
                title.setFocusable(true);
            } catch (Exception e) {
                e.printStackTrace();
            } catch (OutOfMemoryError e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @Title: showAlertDialog
     * @Description: 显示dialog<br/>
     * isShowCanCel 是否显示取消按钮
     */
    public static void showAlertDialog(Context context, int titleId, int messageId, OnClickListener listener,
                                       boolean isShowCanCel) {
        showAlertDialog(context, titleId, messageId, listener, isShowCanCel, R.string.submit, R.string.share_cancel);
    }

    /**
     * @Title: showAlertDialog
     * @Description: 显示dialog<br/>
     * isShowCanCel 是否显示取消按钮
     */
    public static void showAlertDialog(Context context, int titleId, int messageId, OnClickListener listener,
                                       boolean isShowCanCel, int... resId) {
        if (!isShowCanCel) {
            showAlertDialog(context, titleId, messageId, listener);
        }
        int cancelResId = 0;
        int finshResId = 0;
        if (resId.length <= 0) {
            cancelResId = R.string.share_cancel;
            finshResId = R.string.submit;
        } else if (resId.length == 1) {
            cancelResId = R.string.share_cancel;
            finshResId = resId[0];
        } else if (resId.length == 2) {
            cancelResId = resId[1];
            finshResId = resId[0];
        } else {
            throw new RuntimeException("Parameters resId length exceeds limit! Requires only two parameters");
        }
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);

        alertDialog.setMessage(messageId);
        alertDialog.setPositiveButton(finshResId, listener);
        alertDialog.setNegativeButton(cancelResId, new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        showDialog(context, alertDialog);
    }

    public static void showResultAlertDialog(Context context, boolean tag, RemoteCommandsType requestType,
                                             ErrorInfo errorInfo, AlertDialogEventProxy eventProxy) {
        String make = getVehicleName(context);
        StringBuffer strBuild = new StringBuffer();
        StringBuffer strBuildTBT = new StringBuffer();
        switch (requestType) {
            case COMMANDS_UNLOCK_DOOR:
                strBuild.append(make);
                if (tag) {
                    strBuild.append(context.getString(R.string.unlock_success));
                } else {
                    strBuild.append(context.getString(R.string.unlock_failure));
                    strBuild.append("(" + errorInfo.getCode().replaceAll("ONS-", "0").replaceAll("SOMP-", "1") + ")");
                }
                break;
            case COMMANDS_LOCK_DOOR:
                strBuild.append(make);
                if (tag) {
                    strBuild.append(context.getString(R.string.lock_success));
                } else {
                    strBuild.append(context.getString(R.string.lock_failure));
                    strBuild.append("(" + errorInfo.getCode().replaceAll("ONS-", "0").replaceAll("SOMP-", "1") + ")");
                }
                break;
            case COMMANDS_START:
                strBuild.append(make);
                if (tag) {
                    strBuild.append(context.getString(R.string.start_success));
                } else {
                    strBuild.append(context.getString(R.string.start_failure));
                    strBuild.append("(" + errorInfo.getCode().replaceAll("ONS-", "0").replaceAll("SOMP-", "1") + ")");
                }
                break;
            case COMMANDS_CANCEL_START:
                strBuild.append(make);
                if (tag) {
                    strBuild.append(context.getString(R.string.stop_success));
                } else {
                    strBuild.append(context.getString(R.string.stop_failure));
                    strBuild.append("(" + errorInfo.getCode().replaceAll("ONS-", "0").replaceAll("SOMP-", "1") + ")");
                }
                break;
            case COMMANDS_ALERT:
                strBuild.append(make);
                if (tag) {
                    strBuild.append(context.getString(R.string.alert_success));
                } else {
                    strBuild.append(context.getString(R.string.alert_failure));
                    strBuild.append("(" + errorInfo.getCode().replaceAll("ONS-", "0").replaceAll("SOMP-", "1") + ")");
                }
                break;
            case COMMANDS_TBT_ROUTE:
                if (tag) {
                    strBuildTBT.append(context.getString(R.string.send_to_tbt_success));
                } else {
                    strBuildTBT.append(context.getString(R.string.send_to_tbt_failed));
                    strBuildTBT.append("(" + errorInfo.getCode().replaceAll("ONS-", "0").replaceAll("SOMP-", "1") + ")");
                }
                break;
            case COMMANDS_NAV_DESTINATION:
                if (tag) {
                    strBuildTBT.append(context.getString(R.string.send_to_odd_success));
                } else {
                    strBuildTBT.append(context.getString(R.string.send_to_odd_failed));
                    strBuildTBT.append("(" + errorInfo.getCode().replaceAll("ONS-", "0").replaceAll("SOMP-", "1") + ")");
                }
                break;
            case COMMANDS_LOCATION:
                strBuild = new StringBuffer();
                strBuild.append(errorInfo.getMsg());
                strBuild.append("(" + errorInfo.getCode().replaceAll("ONS-", "0").replaceAll("SOMP-", "1") + ")");
                break;
            case COMMANDS_DIAGNOSTICS:
                if (tag) {
                } else {
                    strBuild = new StringBuffer();
                    strBuild.append(errorInfo.getMsg());
                    strBuild.append("(" + errorInfo.getCode().replaceAll("ONS-", "0").replaceAll("SOMP-", "1") + ")");
                }
                break;
            case COMMANDS_HISTROY:
                break;
            default:
                break;
        }
        if (requestType == RemoteCommandsType.COMMANDS_LOCATION
                || requestType == RemoteCommandsType.COMMANDS_DIAGNOSTICS) {
            showAlertDialog(context, context.getString(R.string.dialog_warning), strBuild.toString(), eventProxy);
        } else if (requestType == RemoteCommandsType.COMMANDS_TBT_ROUTE
                || requestType == RemoteCommandsType.COMMANDS_NAV_DESTINATION) {
            showAlertDialog(context, context.getString(R.string.dialog_warning), strBuildTBT.toString(), eventProxy);
        } else {
            showAlertDialog(context, context.getString(R.string.remote_control), strBuild.toString(), eventProxy);
        }
    }

    public static void showResultSystemAlertDialog(Context context, boolean tag, RemoteCommandsType requestType,
                                                   ErrorInfo errorInfo, AlertDialogEventProxy eventProxy) {
        String make = getVehicleName(context);
        StringBuffer strBuild = new StringBuffer();
        StringBuffer strBuildTBT = new StringBuffer();
        switch (requestType) {
            case COMMANDS_UNLOCK_DOOR:
                strBuild.append(make);
                if (tag) {
                    strBuild.append(context.getString(R.string.unlock_success));
                } else {
                    strBuild.append(context.getString(R.string.unlock_failure));
                    strBuild.append("(" + errorInfo.getCode().replaceAll("ONS-", "0").replaceAll("SOMP-", "1") + ")");
                }
                break;
            case COMMANDS_LOCK_DOOR:
                strBuild.append(make);
                if (tag) {
                    strBuild.append(context.getString(R.string.lock_success));
                } else {
                    strBuild.append(context.getString(R.string.lock_failure));
                    strBuild.append("(" + errorInfo.getCode().replaceAll("ONS-", "0").replaceAll("SOMP-", "1") + ")");
                }
                break;
            case COMMANDS_START:
                strBuild.append(make);
                if (tag) {
                    strBuild.append(context.getString(R.string.start_success));
                } else {
                    strBuild.append(context.getString(R.string.start_failure));
                    strBuild.append("(" + errorInfo.getCode().replaceAll("ONS-", "0").replaceAll("SOMP-", "1") + ")");
                }
                break;
            case COMMANDS_CANCEL_START:
                strBuild.append(make);
                if (tag) {
                    strBuild.append(context.getString(R.string.stop_success));
                } else {
                    strBuild.append(context.getString(R.string.stop_failure));
                    strBuild.append("(" + errorInfo.getCode().replaceAll("ONS-", "0").replaceAll("SOMP-", "1") + ")");
                }
                break;
            case COMMANDS_ALERT:
                strBuild.append(make);
                if (tag) {
                    strBuild.append(context.getString(R.string.alert_success));
                } else {
                    strBuild.append(context.getString(R.string.alert_failure));
                    strBuild.append("(" + errorInfo.getCode().replaceAll("ONS-", "0").replaceAll("SOMP-", "1") + ")");
                }
                break;
            case COMMANDS_TBT_ROUTE:
                if (tag) {
                    strBuildTBT.append(context.getString(R.string.send_to_tbt_success));
                } else {
                    strBuildTBT.append(context.getString(R.string.send_to_tbt_failed));
                    strBuildTBT.append("(" + errorInfo.getCode().replaceAll("ONS-", "0").replaceAll("SOMP-", "1") + ")");
                }
                break;
            case COMMANDS_NAV_DESTINATION:
                if (tag) {
                    strBuildTBT.append(context.getString(R.string.send_to_odd_success));
                } else {
                    strBuildTBT.append(context.getString(R.string.send_to_odd_failed));
                    strBuildTBT.append("(" + errorInfo.getCode().replaceAll("ONS-", "0").replaceAll("SOMP-", "1") + ")");
                }
                break;
            case COMMANDS_LOCATION:
                strBuild = new StringBuffer();
                strBuild.append(errorInfo.getMsg());
                strBuild.append("(" + errorInfo.getCode().replaceAll("ONS-", "0").replaceAll("SOMP-", "1") + ")");
                break;
            case COMMANDS_DIAGNOSTICS:
                if (tag) {
                } else {
                    strBuild = new StringBuffer();
                    strBuild.append(errorInfo.getMsg());
                    strBuild.append("(" + errorInfo.getCode().replaceAll("ONS-", "0").replaceAll("SOMP-", "1") + ")");
                }
                break;
            case COMMANDS_HISTROY:
                break;
            default:
                break;
        }
        if (requestType == RemoteCommandsType.COMMANDS_LOCATION
                || requestType == RemoteCommandsType.COMMANDS_DIAGNOSTICS) {
            showAlertDialog(context, context.getString(R.string.dialog_warning), strBuild.toString(), eventProxy);
        } else if (requestType == RemoteCommandsType.COMMANDS_TBT_ROUTE
                || requestType == RemoteCommandsType.COMMANDS_NAV_DESTINATION) {
            showSystemAlertDialog(context, context.getString(R.string.dialog_warning), strBuildTBT.toString(),
                    eventProxy);
        } else {
            showSystemAlertDialog(context, context.getString(R.string.remote_control), strBuild.toString(), eventProxy);
        }
    }


    public static String getResultSystemAlertDialog(Context context, boolean tag, RemoteCommandsType requestType,
                                                    ErrorInfo errorInfo, AlertDialogEventProxy eventProxy) {
        String make = getVehicleName(context);
        StringBuffer strBuild = new StringBuffer();
        StringBuffer strBuildTBT = new StringBuffer();
        switch (requestType) {
            case COMMANDS_UNLOCK_DOOR:
                strBuild.append(make);
                if (tag) {
                    strBuild.append(context.getString(R.string.unlock_success));
                } else {
                    strBuild.append(context.getString(R.string.unlock_failure));
                    strBuild.append("(" + errorInfo.getCode().replaceAll("ONS-", "0").replaceAll("SOMP-", "1") + ")");
                }
                break;
            case COMMANDS_LOCK_DOOR:
                strBuild.append(make);
                if (tag) {
                    strBuild.append(context.getString(R.string.lock_success));
                } else {
                    strBuild.append(context.getString(R.string.lock_failure));
                    strBuild.append("(" + errorInfo.getCode().replaceAll("ONS-", "0").replaceAll("SOMP-", "1") + ")");
                }
                break;
            case COMMANDS_START:
                strBuild.append(make);
                if (tag) {
                    strBuild.append(context.getString(R.string.start_success));
                } else {
                    strBuild.append(context.getString(R.string.start_failure));
                    strBuild.append("(" + errorInfo.getCode().replaceAll("ONS-", "0").replaceAll("SOMP-", "1") + ")");
                }
                break;
            case COMMANDS_CANCEL_START:
                strBuild.append(make);
                if (tag) {
                    strBuild.append(context.getString(R.string.stop_success));
                } else {
                    strBuild.append(context.getString(R.string.stop_failure));
                    strBuild.append("(" + errorInfo.getCode().replaceAll("ONS-", "0").replaceAll("SOMP-", "1") + ")");
                }
                break;
            case COMMANDS_ALERT:
                strBuild.append(make);
                if (tag) {
                    strBuild.append(context.getString(R.string.alert_success));
                } else {
                    strBuild.append(context.getString(R.string.alert_failure));
                    strBuild.append("(" + errorInfo.getCode().replaceAll("ONS-", "0").replaceAll("SOMP-", "1") + ")");
                }
                break;
            case COMMANDS_TBT_ROUTE:
                if (tag) {
                    strBuildTBT.append(context.getString(R.string.send_to_tbt_success));
                } else {
                    strBuildTBT.append(context.getString(R.string.send_to_tbt_failed));
                    strBuildTBT.append("(" + errorInfo.getCode().replaceAll("ONS-", "0").replaceAll("SOMP-", "1") + ")");
                }
                break;
            case COMMANDS_NAV_DESTINATION:
                if (tag) {
                    strBuildTBT.append(context.getString(R.string.send_to_odd_success));
                } else {
                    strBuildTBT.append(context.getString(R.string.send_to_odd_failed));
                    strBuildTBT.append("(" + errorInfo.getCode().replaceAll("ONS-", "0").replaceAll("SOMP-", "1") + ")");
                }
                break;
            case COMMANDS_LOCATION:
                strBuild = new StringBuffer();
                strBuild.append(errorInfo.getMsg());
                strBuild.append("(" + errorInfo.getCode().replaceAll("ONS-", "0").replaceAll("SOMP-", "1") + ")");
                break;
            case COMMANDS_DIAGNOSTICS:
                if (tag) {
                } else {
                    strBuild = new StringBuffer();
                    strBuild.append(errorInfo.getMsg());
                    strBuild.append("(" + errorInfo.getCode().replaceAll("ONS-", "0").replaceAll("SOMP-", "1") + ")");
                }
                break;
            case COMMANDS_HISTROY:
                break;
            default:
                break;
        }
        return strBuild.toString();
    }

    /*
     * 弹出dialog tag 是remoteControl的结果（true 表示 成功， false 表示失败）
     */
    public static void showResultAlertDialog(Context context, boolean tag, RemoteCommandsType requestType,
                                             ErrorInfo errorInfo) {
        showResultAlertDialog(context, tag, requestType, errorInfo, null);
    }

    /*
     * 弹出dialog tag 是remoteControl的结果（true 表示 成功， false 表示失败）
     */
    public static void showResultSystemAlertDialog(Context context, boolean tag, RemoteCommandsType requestType,
                                                   ErrorInfo errorInfo) {
        showResultSystemAlertDialog(context, tag, requestType, errorInfo, null);
    }

    private static String getVehicleName(Context context) {
        if (ApplicationUtil.getInstance().getCurrentVehicle() != null) {
            String make = "", model = "";
            make = ApplicationUtil.getInstance().getCurrentVehicle().getMakeDesc();
            model = ApplicationUtil.getInstance().getCurrentVehicle().getModelDesc();
            return make + " " + model + ",";
        }
        return "";
    }

    public static void showExitDialog(final Activity context) {
        AlertDialog.Builder exitDialog = new AlertDialog.Builder(context);
        exitDialog.setIcon(android.R.drawable.stat_sys_warning);
        exitDialog.setMessage(R.string.exit_string);
        exitDialog.setPositiveButton(R.string.submit, new OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                /* User clicked OK so do some stuff */
                // 取消polling
                BusinessUtil.refreshPolling(context);
                BusinessUtil.clearOnstarAppContext(context);
                // 取消定时刷新token。
                AuthorUtil.getInstance().cancelRegistAlarmReauthentication(context);
                Intent intent = new Intent(Intent.ACTION_MAIN);
                intent.addCategory(Intent.CATEGORY_HOME);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                context.startActivity(intent);
                context.finish();
                android.os.Process.killProcess(android.os.Process.myPid());
            }
        });
        exitDialog.setNegativeButton(R.string.cancel, new OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {

				/* User clicked Cancel so do some stuff */
            }
        });
        if (isAllowShowDialog(context)) {
            exitDialog.show();
        }
    }

    public static void showHelpDialog(Context context, int resId) {

        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setMessage(resId);
        builder.setPositiveButton(R.string.submit, new OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {

				/* User clicked OK so do some stuff */
            }
        });
        builder.show();
    }

    public static void showDialogByExceptionCode(Context context, HttpException e, AlertDialogEventProxy eventProxy) {
        if (context == null) return;
        ErrorInfo errorInfo = ErrorCodeUtil.getErrorInfoByHttpException(context, e);
        showAlertDialog(context, context.getString(R.string.dialog_warning), errorInfo.getMsg(), eventProxy);
    }

    public static void showSystemDialogByExceptionCode(Context context, HttpException e,
                                                       AlertDialogEventProxy eventProxy) {
        ErrorInfo errorInfo = ErrorCodeUtil.getErrorInfoByHttpException(context, e);
        showSystemAlertDialog(context, context.getString(R.string.dialog_warning), errorInfo.getMsg(), eventProxy);
    }

    /**
     * 处理调用MAG接口返回的Exception code，转换对应message
     *
     * @param context
     * @param e
     */
    public static void showDialogByExceptionCode(Context context, HttpException e) {
        showDialogByExceptionCode(context, e, null);
    }

    public static void showDialogByOnstarException(Context context, OnStarException e) {
        showDialogByExceptionCode(context, new HttpException(e.getErrorCode(), e.getMessage()));
    }

    public static void showDialogByOnstarException(Context context, OnStarException e, AlertDialogEventProxy eventProxy) {
        showDialogByExceptionCode(context, new HttpException(e.getErrorCode(), e.getMessage()), eventProxy);
    }

    public interface AlertDialogEventProxy {
        void onPositiveClickListener(DialogInterface dialog);

        void onCancelListener(DialogInterface dialog);
    }


    public static void showAlertDialog(Context context, String msg) {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);

        alertDialog.setMessage(msg);
        alertDialog.setPositiveButton(R.string.submit, new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        requetFocusable(alertDialog, context);
    }

//    public static void showAlertDialog(Context context, int titleId,int msgId) {
//        AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
//        alertDialog.setTitle(titleId);
//        alertDialog.setMessage(msgId);
//        alertDialog.setPositiveButton(R.string.submit, new OnClickListener() {
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//                dialog.dismiss();
//            }
//        });
//        requetFocusable(alertDialog, context);
//    }

    public static void showSmartSettingAlertDialog(Context context,String title, String message, String okBtn, String cancelBtn, OnClickListener okListener,OnClickListener cancelListen) {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
        alertDialog.setTitle(title);
        alertDialog.setMessage(message);
        alertDialog.setPositiveButton(okBtn,okListener);
        alertDialog.setNegativeButton(cancelBtn,cancelListen);
        alertDialog.setCancelable(false);
        requetFocusable(alertDialog, context);
    }

    public static void showOverallAlertDialog(Context context,String title, String message, String okBtn, String cancelBtn, OnClickListener okListener,OnClickListener cancelListen) {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
        alertDialog.setTitle(title);
        alertDialog.setMessage(message);
        alertDialog.setPositiveButton(okBtn,okListener);
        alertDialog.setNegativeButton(cancelBtn,cancelListen);
        if (isAllowShowDialog(context)) {
            AlertDialog dialog = alertDialog.create();
            try {
                dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
                dialog.show();
                // 反射获取当前Dialog TextView对象
                Field mAlert = AlertDialog.class.getDeclaredField("mAlert");
                mAlert.setAccessible(true);
                Object alertController = mAlert.get(dialog);
                Field mTitleView = alertController.getClass().getDeclaredField("mMessageView");
                mTitleView.setAccessible(true);
                TextView titleView = (TextView) mTitleView.get(alertController);
                titleView.setFocusable(true);
            } catch (Exception e) {
                e.printStackTrace();
            } catch (OutOfMemoryError e) {
                e.printStackTrace();
            }
        }
    }
}
